<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <el-input v-model="pageFrom.serialNumber" placeholder="请输入品牌名称"></el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" icon="el-icon-search">搜索</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-button type="primary" @click="openDialog">添加设备</el-button>
      <el-button type="primary" @click="">开始群控</el-button>
    </el-row>
    <el-table
      v-loading="listLoading"
      :data="anDeviceList"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="序号" align="center" width="100"
                       type="index"
      ></el-table-column>
      <el-table-column label="设备名称" align="center">
        <template slot-scope="scope">
          {{ scope.row.deviceName }}
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center">
        <template slot-scope="scope">
          {{ scope.row.brandName }}
        </template>
      </el-table-column>
      <el-table-column label="型号" align="center">
        <template slot-scope="scope">
          {{ scope.row.modelName }}
        </template>
      </el-table-column>
      <el-table-column label="设备IP" align="center">
        <template slot-scope="scope">
          {{ scope.row.deviceIp }}
        </template>
      </el-table-column>
      <el-table-column label="设备标识" align="center">
        <template slot-scope="scope">
          {{ scope.row.serialNumber }}
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" @click="editDialog(scope.row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="delConfirm(scope.row)">删除</el-button>
          <el-button type="primary" icon="el-icon-check" @click="openViewControlDialog(scope.row)">控制</el-button>
          <el-button type="primary" icon="el-icon-check">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageFrom.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageFrom.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageFrom.total">
      </el-pagination>
    </div>


    <el-dialog :title="dialogForm.title" :visible.sync="dialogForm.visible" :close-on-click-modal="false"
               @close="closeDialog">
      <el-form :model="anDeviceForm">
        <el-tag>扫描二维下载app获取手机序列号</el-tag>
        <el-form-item label="二维码">
          <el-image :src="qrCode"></el-image>
        </el-form-item>
        <el-form-item label="序列号">
          <el-input v-model="anDeviceForm.serialNumber"></el-input>
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="anDeviceForm.deviceName"></el-input>
        </el-form-item>
        <el-form-item label="设备ip">
          <el-input v-model="anDeviceForm.deviceIp"></el-input>
        </el-form-item>
        <el-tag>请使用usb连接</el-tag>
        <el-form-item label="连接测试">
          <el-button type="success" @click="connectAtxInit">测试连接</el-button>
        </el-form-item>
        <div>
          <el-form-item label="品牌">
            <el-input v-model="anDeviceForm.brandName"></el-input>
          </el-form-item>
          <el-form-item label="型号">
            <el-input v-model="anDeviceForm.modelName"></el-input>
          </el-form-item>
          <el-form-item label="内存">
            <el-input v-model="anDeviceForm.memory"></el-input>
          </el-form-item>
          <el-form-item label="CUP">
            <el-input v-model="anDeviceForm.cpu"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog id="elDialogViewControl" customClass="customWidth"  :title="viewControlDialog.title" :close-on-click-modal="false"
               :visible.sync="viewControlDialog.visible" @close="closeViewControlDialog">
      <div id="dialogdiv">
        <div id="canvasdiv">
          <div style="margin: 5px 0px">
            <el-button type="primary" @click="refreshImg(viewControl.agentUrl)">刷新画面 fps: <span v-text="viewControl.fps.toFixed(1)"></span>
            </el-button>
          </div>
          <div style="margin: 5px 0px">
            <el-button type="primary" @click="refreshImg">切换</el-button>
            <el-button type="primary" @click="refreshImg">主页</el-button>
            <el-button type="primary" @click="refreshImg">返回</el-button>
          </div>
          <div>
            <img ref="imgRef" style="border: 1px solid blue;"/>
          </div>
        </div>
        <div id="gcontrol">
          <el-button type="primary">群控设备列表</el-button>
          <el-tree
            :data="devicesTree"
            show-checkbox
            node-key="id"
            default-expand-all
            @check-change="handleCheckChange"
            :expand-on-click-node="false">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  type="text"
                  size="mini"
                  @click="() => switchMiniCap(data)">
                  切换
                </el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </div>
    </el-dialog>
  </div>
</template>


<script>
  import {
    getDevicesTree,
    atxInit,
    getCurrentApk,
    getAnDeviceListPage,
    addAnDevice,
    updAnDevice,
    delAnDevice,
    getAnDeviceById
  } from '@/api/andevice'


  export default {
    data() {
      return {
        devicesTree: [],
        viewControl: {
          ws_minicap: {},
          ws_minitouch: {},
          ws_minitouchArray: [],
          agentUrl: "",
          img: {},
          rotation: 0,
          fps: 0,
          periodImageCount: 0,
        },
        viewControlDialog: {
          visible: false,
          title: "远程控制",
        },
        // 分页查询参数对象
        pageFrom: {
          serialNumber: "",
          total: 1,
          current: 1,
          size: 10
        },
        dialogForm: {
          visible: false,
          title: "新增",
        },
        qrCode: "",
        formRules: {},
        anDeviceList: [],
        listLoading: true,
        anDeviceForm: {
          id: "0",
          brandName: "",
          modelName: "",
          memory: "",
          cpu: "",
          deviceName: "",
          deviceIp: "",
          serialNumber: ""
        }

      }
    },
    created() {
      this.fetchData(this.pageFrom)
    },
    mounted() {
    },
    methods: {
      handleCheckChange(data, checked, indeterminate) {
        console.log(data, checked, indeterminate);
        if(checked){
          //选中数组里添加 ws
          //连接websocket
         let ws_miniTouch  = this.initMiniTouchOther(data.agentUrl)
          //放到数组中
         this.viewControl.ws_minitouchArray.push(ws_miniTouch);
         console.log("最终数组"+this.viewControl.ws_minitouchArray)
        }else {
          //取消选中数组里删除 ws
          this.viewControl.ws_minitouchArray = this.viewControl.ws_minitouchArray.filter((item, i) => {
            //console.log("循环==i==", i);
            return item.url.indexOf(data.agentUrl) === -1
          })
          console.log("最终数组"+this.viewControl.ws_minitouchArray)
        }
      },
      openViewControlDialog(row) {
        this.viewControlDialog.visible = true
        this.$nextTick(() => {
          this.viewControl.img = this.$refs.imgRef
          this.viewControl.img.maxWidth  = "800px"
          this.viewControl.agentUrl = row.agentUrl
          this.initMiniCap(row.agentUrl)
          this.initMiniTouch(row.agentUrl)
          setInterval(() => {
            this.viewControl.fps = this.viewControl.periodImageCount / 0.5
            this.viewControl.periodImageCount = 0
          }, 500)
        })

        getDevicesTree().then(response => {
          this.devicesTree = response.data
        })

      },
      closeViewControlDialog() {
        this.viewControl.ws_minicap.close()
        this.viewControl.ws_minitouch.close()
        this.viewControl.img.src = ""
      },
      connectAtxInit() {
        atxInit(this.anDeviceForm).then(response => {
          this.anDeviceForm.brandName = response.data.brand;
          this.anDeviceForm.modelName = response.data.model;
          this.anDeviceForm.memory = response.data.memory.around;
          this.anDeviceForm.cpu = response.data.cpu.hardware;
          this.anDeviceForm.androidVersion = response.data.version;
          this.anDeviceForm.androidSdk = response.data.sdk;
        }).catch(error => {

        });
      },
      closeDialog() {
        //this.dialogForm.visible = false
      },

      clearForm() {
      },
      onSubmit() {
        if (this.anDeviceForm.id === "0") {
          addAnDevice(this.anDeviceForm).then(response => {
            this.clearForm();
          }).catch(error => {
            this.clearForm();
          });
        } else {
          updAnDevice(this.anDeviceForm).then(response => {
            this.clearForm();
          }).catch(error => {
            this.clearForm();
          });
        }
        this.closeDialog()
        this.fetchData(this.pageFrom)
      },
      openDialog() {
        this.dialogForm.visible = true
        this.dialogForm.title = "新增"
        getCurrentApk().then(response => {
          this.qrCode = response.data.qrCode
        })
      },
      editDialog(row) {
        this.dialogForm.visible = true
        this.dialogForm.title = "修改"

        getAnDeviceById(row.id).then(response => {
          this.anDeviceForm.id = response.data.id
        })
      },
      delConfirm(row) {
        console.log(row.id)
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delAnDevice(row.id).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchData(this.pageFrom)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      fetchData(data) {
        this.listLoading = true
        getAnDeviceListPage(data).then(response => {
          this.anDeviceList = response.data.records
          this.listLoading = false
          this.pageFrom.size = parseInt(response.data.size)
          this.pageFrom.total = parseInt(response.data.total)
        })
      },
      handleSizeChange(val) {
        this.pageFrom.size = val
        this.fetchData(this.pageFrom)
      },
      handleCurrentChange(val) {
        this.pageFrom.current = val
        this.fetchData(this.pageFrom)
      },
      refreshImg(agentUrl) {
        this.viewControl.img.src = `http://` + agentUrl + `//screenshot?t=${new Date().getTime()}`
      },
      initMiniCap(agentUrl) {
        this.viewControl.ws_minicap = new WebSocket('ws://' + agentUrl + "/minicap")
        this.viewControl.ws_minicap.onopen = function () {
          console.log('onopen', arguments)
        }
        this.viewControl.ws_minicap.onclose = () => {
          console.log("Websocket closed, Refresh to reload.")
        }
        this.viewControl.ws_minicap.onerror = function () {
          console.log('onerror', arguments)
        }
        this.viewControl.ws_minicap.onmessage = (message) => {
          if (message.data instanceof Blob) {
            this.viewControl.periodImageCount += 1 // help for calculate fps
            let blob = new Blob([message.data], {
              type: 'image/jpeg'
            })
            let URL = window.URL || window.webkitURL
            let u = URL.createObjectURL(blob)
            this.viewControl.img.src = u
          } else if (/data size: /.test(message.data)) {
            // console.log("receive message:", message.data)
          } else if (/^rotation/.test(message.data)) {
            this.viewControl.rotation = parseInt(message.data.substr('rotation '.length), 10);
            console.log("rotation:", this.viewControl.rotation)
          } else {
            console.log("receive message:", message.data)
          }
        }

        this.refreshImg(agentUrl);
      },
      switchMiniCap(data) {
        this.viewControl.ws_minicap.close()
        this.viewControl.img.src = ""
        this.viewControl.agentUrl = data.agentUrl
        //console.log(data.agentUrl)
        this.initMiniCap(data.agentUrl);
      },
      coords(boundingW, boundingH, relX, relY, rotation) {
        let w, h, x, y;

        switch (rotation) {
          case 0:
            w = boundingW
            h = boundingH
            x = relX
            y = relY
            break
          case 90:
            w = boundingH
            h = boundingW
            x = boundingH - relY
            y = relX
            break
          case 180:
            w = boundingW
            h = boundingH
            x = boundingW - relX
            y = boundingH - relY
            break
          case 270:
            w = boundingH
            h = boundingW
            x = relY
            y = boundingW - relX
            break
        }

        return {
          xP: x / w,
          yP: y / h,
        }
      },
      touchSync(operation, event) {
        let e = event;
        if (e.originalEvent) {
          e = e.originalEvent
        }
        e.preventDefault()
        let x = e.offsetX
        let y = e.offsetY
        let w = e.target.clientWidth
        let h = e.target.clientHeight

        let scaled = this.coords(w, h, x, y, this.viewControl.rotation);
        this.viewControl.ws_minitouch.send(JSON.stringify({
          operation: operation, // u, d, c, w
          index: 0,
          pressure: 0.5,
          xP: scaled.xP,
          yP: scaled.yP,
        }))
        this.viewControl.ws_minitouch.send(JSON.stringify({operation: 'c'}))
        this.viewControl.ws_minitouchArray.forEach((item,i) => {
            item.send(JSON.stringify({
             operation: operation, // u, d, c, w
             index: 0,
             pressure: 0.5,
             xP: scaled.xP,
             yP: scaled.yP,
           }))
            item.send(JSON.stringify({operation: 'c'}))
        });
      },
      initMiniTouch(agentUrl){
        this.viewControl.ws_minitouch = new WebSocket("ws://" + agentUrl + "/minitouch")
        this.viewControl.ws_minitouch.onopen = (ret) => {
          this.viewControl.ws_minitouch.send(JSON.stringify({ // touch reset, fix when device is outof control
            operation: "r",
          }))
          this.viewControl.img.addEventListener("mousedown",  this.mouseDownListener)
        }
        this.viewControl.ws_minitouch.onmessage = (message) => {
          console.log("minitouch recv", message)
        }
        this.viewControl.ws_minitouch.onclose = () => {
          console.log("minitouch closed")
          this.viewControl.img.removeEventListener("mousedown",  this.mouseDownListener)
        }
      },
      initMiniTouchOther(agentUrl){
        let ws_miniTouch = new WebSocket("ws://" + agentUrl + "/minitouch")
        ws_miniTouch.onopen = (ret) => {
          this.viewControl.ws_minitouch.send(JSON.stringify({ // touch reset, fix when device is outof control
            operation: "r",
          }))
        }
        ws_miniTouch.onmessage = (message) => {
          console.log("minitouch recv", message)
        }
        ws_miniTouch.onclose = () => {
          console.log("minitouch closed")
        }
        return ws_miniTouch
      },
      mouseMoveListener(event) {
         this.touchSync('m', event)
      },
      mouseUpListener(event) {
        this.touchSync('u', event)
        this.viewControl.img.removeEventListener('mousemove', this.mouseMoveListener);
        document.removeEventListener('mouseup',  this.mouseUpListener);
      },
      mouseDownListener(event) {
        this.touchSync('d', event)
        this.viewControl.img.addEventListener('mousemove',  this.mouseMoveListener);
        document.addEventListener("mouseup",  this.mouseUpListener)
      }

  }
  }
</script>
<style>

  #dialogdiv {
    display: flex;
    min-width: 800px;
  }

  #canvasdiv {
    max-width: 800px;
  }

  #gcontrol {
  }
  .customWidth{
    width:60%;
  }
</style>
